package com.huaxinkaiye.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ToolUtil {

    private final static String IVKEY = "AESAPPCLIENT_KEY";

    public  String encrypt(String data,String key) {
        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            SecretKeySpec keyspec = new SecretKeySpec(fullZore(key,blockSize), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(fullZore(IVKEY,blockSize));
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(fullZore(data,blockSize));
            return new String(Base64.encode(encrypted)).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
   public static String  getTime(int time){    
       SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
       Date d1=new Date(time);  
       String t1=format.format(d1);  
       return  t1; 
   } 
    public  String decrypt(String data,String key) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            SecretKeySpec keyspec = new SecretKeySpec(fullZore(key,blockSize), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(fullZore(IVKEY,blockSize));
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] decrypted = cipher.doFinal(Base64.decode(data));
            return new String(decrypted).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public  byte[] fullZore(String data,int blockSize){
        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        return plaintext;
    }

    public static void main(String[] args){
        int id = 3488;
        ToolUtil m = new ToolUtil();
        String en = m.encrypt(String.valueOf(id),IVKEY);
        String de = m.decrypt(en ,IVKEY);
        System.out.println(en+" <-- "+de);
    }
}
